package praktikumid.w10.p5;

import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.MouseEvent;

/**
 * Rectangle, defined by the start point
 * and width/height.
 * @author Ago
 *
 */
public class Rectangle extends Shape {

	/**
	 * Starting point (not necessarily the leftmost
	 * upper point).
	 */
	private Point start; 
	/**
	 * Width of the rectangle.
	 */
	private int width = 0;
	/**
	 * Height of the rectangle.
	 */
	private int height = 0;
	
	@Override
	public void paintComponent(Graphics g) {
		// draws the rectangle
		if (start != null) {
			// first we need to find the leftmost upper
			// point, because drawing rectangle
			// on Graphics starts always from leftmost upper
			// point.
			int left = Math.min(start.x, start.x + width);
			int up = Math.min(start.y, start.y + height);
			g.drawRect(left, up, Math.abs(width), Math.abs(height));
		}
	}
	
	@Override
	public void mouseDragged(MouseEvent e) {
		if (start == null) {
			// if we start dragging, let's set start point
			// (note that this should be done already
			// in mousePressed; therefore it might not
			// be needed here)
			start = e.getPoint();
		} else {
			// if we continue dragging, let's change width/height
			width = e.getPoint().x - start.x;
			height = e.getPoint().y - start.y;
		}
	}
	
	@Override
	public void mouseReleased(MouseEvent e) {
		// if button is released (after drag or just pressed),
		// we finish the shape.
		isFinished = true;
	}
	
	@Override
	public void mousePressed(MouseEvent e) {
		if (start == null) {
			// if mouse pressed, we set the start point
			start = e.getPoint();
		}
	}
	@Override
	public int getDistance(Point p) {
		// finds the distance
		// we try to find the closest edge
		// (note that this might not be correct)
		if (start != null) {
			int d = p.x - start.x;
			d = Math.min(d, p.x - start.x + width);
			d = Math.min(d, p.y - start.y);
			d = Math.min(d, p.y - start.y + height);
			return d;
		}
		return Integer.MAX_VALUE;
	}
	
	@Override
	public void move(int dx, int dy) {
		// let's move start point
		start.x += dx;
		start.y += dy;
	}
}
